    var     AAUMxml     =   "https://members.adam.com.au/um1.5/usage.xml";  

    var     xmlHttp     =   new XMLHttpRequest();
    var     toolTip     =   new Array();
    var     adamPlans   =   new Array();
    var     errMsg      =   new Array();
    var     cycleint    =   0;
    var     rotateTimer =   0;
    var     rotateTime  =   16000;           // Milliseconds between status rotations.
    var     updateTime  =   1800000;          // Milliseconds between updates.

    
    
    // Variables to hold account information retrieved from the Gadget settings.
    var aaConfig = {
        userName:         "",
        userPass:         ""
    };
    
    // Variables to be filled with usage data from XML feed.
    var aaData = {
        TotalData:        0,
        TotalUsenetData:  0,
        DaysRemaining:    0,
        TotalDays:        0,
        DaysUsed:         0,
        Plan:             "",

        usedTotData:      0,
        usedExtData:      0,
        usedUplData:      0,
        usedNewsData:     0,
        usedIntData:      0
   };
   
   // Array of plans offered by Adam. 
   adamPlans['70'] =      "70MB";
   adamPlans['500'] =     "500MB";
   adamPlans['5000'] =    "5GB";
   adamPlans['10000'] =   "10GB";
   adamPlans['20000'] =   "20GB";
   adamPlans['40000'] =   "40GB";
   adamPlans['60000'] =   "40GB";
   adamPlans['80000'] =   "80GB";
   
   //Array of generic Error Messages
   errMsg['no_cred'] =    "errorCred";
   errMsg['auth'] =       "errorAuth";
   errMsg['data'] =       "errorData";
   errMsg['none'] =       "errorNone";
   

   function getCred() {
       aaConfig.userName = System.Gadget.Settings.readString("username");
       aaConfig.userPass = System.Gadget.Settings.readString("password");    
 
   }

   function getDaysRemaining(startDate) {
        todaysDate =        Date.today();
        quotaStartDate =    Date.parse(startDate).add(1).months();
        daysRemaining =     Math.ceil((quotaStartDate - todaysDate) / (1000*60*60*24));
        return              daysRemaining;       
        
   }
   
   function getTotalDays(startDate) { 
        oldStartDate =      Date.parse(startDate);
        quotaStartDate =    Date.parse(startDate).add(1).months();
        totalDays =         Math.ceil((quotaStartDate - oldStartDate) / (1000*60*60*24));
        return              totalDays;
        
   }
   
   function throwError(msg) {
        $(errMsg[msg]).setStyle({display: "Block"});
   }
   
   function hideError() {
        $('errorCred').setStyle({display: "none"});
        $('errorAuth').setStyle({display: "none"});
        $('errorData').setStyle({display: "none"});
        $('errorNone').setStyle({display: "none"});
        
   }

   function addCommas(nStr) {
	    nStr += '';
	    x = nStr.split('.');
	    x1 = x[0];
	    x2 = x.length > 1 ? '.' + x[1] : '';
	    var rgx = /(\d+)(\d{3})/;
	    while (rgx.test(x1)) {
		    x1 = x1.replace(rgx, '$1' + ',' + '$2');
	    }
	    return x1 + x2;
    }
    
    
    function getPerc(p1, p2, p3) {
        if (p1 == 0) { return 0; }
        else {
           perc = (p1 / p2) * p3;
           if (perc > 100) {
                return 100;
           }
           else { return perc; }
        }
    }
    
    
    
    function loadXML(xmlUrl, userName, userPass) { 
                       
            try {
                xmlHttp.open("GET", xmlUrl, false, userName, userPass);
                xmlHttp.send(null);
                }
            catch(e) {
                throwError('data');
            }
            
    }
    
    function loadData() {
  
        AAUMurl = AAUMxml + "?ref=AAUMv2.Vista.Gadget&randomkey=" + Math.random();
          
        getCred();
        if (aaConfig.userName == "" || aaConfig.userPass == "") {
            throwError('no_cred');
        }
        else {
            x = loadXML(AAUMurl, aaConfig.userName, aaConfig.userPass)
        }
    }

    function parseData() {

    
    //if (xmlHttp.readyState == 4) {

        if (xmlHttp.status == 401) { 
                    throwError('auth');
        }
   
        else if (xmlHttp.status == 200) { 
            xmlData =                  xmlHttp.responseXML.documentElement;
                      
            if (!xmlData) {
                    throwError('data');
            
            }

            accTag =                   xmlData.getElementsByTagName("Account")[0];
            subAccTag =                xmlData.getElementsByTagName("SubAccount")[0];
            aaData.TotalData =         accTag.childNodes[0].text;
            aaData.TotalUsenetData =   accTag.childNodes[1].text;
            aaData.Plan =              accTag.childNodes[3].text; 
            
            aaData.usedTotData =       subAccTag.childNodes[1].text;
            aaData.usedExtData =       subAccTag.childNodes[2].text;             
            aaData.usedUplData =       subAccTag.childNodes[3].text;
            aaData.usedNewsData =      subAccTag.childNodes[4].text;
            aaData.usedIntData =       aaData.usedTotData - aaData.usedExtData;
            
            
            aaData.DaysRemaining =     getDaysRemaining(accTag.childNodes[2].text);
            aaData.TotalDays =         getTotalDays(accTag.childNodes[2].text);
            aaData.DaysUsed =          aaData.TotalDays - aaData.DaysRemaining;
           
          }
         else {
                    throwError('data');
         }
       //}     
    }
    
    
    function defToolTip() {
        toolTip[0] = '<span class="toolTipHead">' + aaData.Plan + ' ' + adamPlans[aaData.TotalData] + '</span><br />' + aaData.DaysRemaining + ' days remaining<br />';
        toolTip[1] = '<span class="toolTipHead" style="color: #40B3D9;">External Data</span><br />' + addCommas(aaData.usedExtData) + ' of ' + addCommas(aaData.TotalData) + ' MB';
        toolTip[2] = '<span class="toolTipHead" style="color: #FFAF36;">Internal Data</span><br />' + addCommas(aaData.usedIntData) + ' of ' + addCommas(aaData.TotalData) + ' MB';
        toolTip[3] = '<span class="toolTipHead" style="color: #B3D941;">Uploaded Data</span><br />' + addCommas(aaData.usedUplData) + ' of ' + addCommas(aaData.TotalData) + ' MB';
        toolTip[4] = '<span class="toolTipHead" style="color: #8D8D8D;">Usenet Data</span><br />' +   addCommas(aaData.usedNewsData) + ' of ' + addCommas(aaData.TotalUsenetData) + ' MB';    
    }
    
    function writePercentages() {
            $('perc_days').innerHTML =  aaData.DaysRemaining + 'd'; 
            $('perc_ext').innerHTML =   Math.ceil(getPerc(aaData.usedExtData, aaData.TotalData, 100)) + '%';
            $('perc_int').innerHTML =   Math.ceil(getPerc(aaData.usedIntData, aaData.TotalData, 100)) + '%';
            $('perc_upl').innerHTML =   Math.ceil(getPerc(aaData.usedUplData, aaData.TotalData, 100)) + '%';
            $('perc_news').innerHTML =  Math.ceil(getPerc(aaData.usedNewsData, aaData.TotalUsenetData, 100)) + '%'; 

    }

    function fillBars() { 
            $('fill_days').setStyle({width: getPerc(aaData.DaysUsed, aaData.TotalDays, 93)});
            $('fill_ext').setStyle({width: getPerc(aaData.usedExtData, aaData.TotalData, 93)});
            $('fill_int').setStyle({width: getPerc(aaData.usedIntData, aaData.TotalData, 93)});
            $('fill_upl').setStyle({width: getPerc(aaData.usedUplData, aaData.TotalData, 93)});
            $('fill_news').setStyle({width: getPerc(aaData.usedNewsData, aaData.TotalUsenetData, 93)});    
                   
    }
       
   function toolTipFadeOut(){
        Effect.Fade('toolTipBox', {afterFinish: toolTipFadeIn});
        
    }
    
    function toolTipFadeIn(){
        if (cycleint < toolTip.length) {
            $('toolTipBox').innerHTML = toolTip[cycleint];
            Effect.Appear('toolTipBox', {to: .99});
            cycleint++;
        }
        else {
            cycleint = 0;
            toolTipFadeIn();
        }
        
    }
    
    function startRotation() {
        rotateTimer = window.setInterval(toolTipFadeOut, rotateTime);
        
    }
    
    function showTip(id, idno) {
        Effect.Pulsate('fill_' + id, {pulses: 1, duration:.35, from:0.2});
        cycleint = idno;
        window.clearInterval(rotateTimer);
        toolTipFadeIn();
        
    }
    
    function hideTip() {
        startRotation();
        
    }
    
    function initialise() {
        hideError();
        loadData();
        parseData();
        writePercentages();
        fillBars();
        defToolTip();
        startRotation(); 
        toolTipFadeIn();

    }
    
    function refreshInt() {
        hideError();
        loadData();
        parseData();
        writePercentages();
        fillBars();
        defToolTip();
        
    }

   document.onreadystatechange = function() {   
        if (document.readyState == "complete") { 
        
            System.Gadget.settingsUI = "settings.html";
            System.Gadget.onSettingsClosed = settingsClosed;
            updateTimer = window.setInterval(refreshInt, updateTime);
            initialise();

       }
    }

   function settingsClosed() {
       // if (event.closeAction == event.Action.commit) { 
             hideError();
             refreshInt();
             startRotation();
             toolTipFadeIn();     
                
       // }
    }
